package com.sdkj.fixed.asset.assets.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.sdkj.fixed.asset.api.assets.in_vo.*;
import com.sdkj.fixed.asset.api.login.pojo.LoginUser;
import com.sdkj.fixed.asset.assets.mapper.*;
import com.sdkj.fixed.asset.assets.util.CacheUtils;
import com.sdkj.fixed.asset.assets.util.DateTools;
import com.sdkj.fixed.asset.assets.util.JwtTokenUtil;
import com.sdkj.fixed.asset.assets.util.RedisUtil;
import com.sdkj.fixed.asset.common.base.BaseMapper;
import com.sdkj.fixed.asset.common.base.BaseService;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.common.utils.JpushClientUtil;
import com.sdkj.fixed.asset.common.utils.TimeTool;
import com.sdkj.fixed.asset.pojo.assets.*;
import com.sdkj.fixed.asset.pojo.system.PushManagement;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author niuliwei
 * @description 借用申请
 * @date 2020/7/28 15:19
 */
@Service
public class BorrowApplyService extends BaseService<BorrowApply> {
    private static final Logger log = LoggerFactory.getLogger(BorrowApplyService.class);
    @Autowired
    private BorrowApplyMapper borrowApplyMapper;
    @Autowired
    private BorrowApplyAssetsMapper borrowApplyAssetsMapper;
    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private StandModelMapper standModelMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private CacheUtils cacheUtils;
    @Autowired
    private BorowService borowService;
    @Autowired
    private BorrowIssueMapper borrowIssueMapper;
    @Autowired
    private PushManagementMapper pushMapper;

    @Override
    public BaseMapper getMapper() {
        return borrowApplyMapper;
    }

    //获取订单号
    private String getNumber(String key, String orgId) {
        Long incr = redisUtil.getIncr(key +"_"+ orgId +"_"+ DateTools.dateToString(new Date(), "yyyyMMdd"), DateTools.expiresTime());
        if (incr == 0) {
            incr = redisUtil.getIncr(key +"_"+ orgId +"_"+ DateTools.dateToString(new Date(), "yyyyMMdd"), DateTools.expiresTime());
        }
        DecimalFormat df = new DecimalFormat("0000");
        return key + DateTools.dateToString(new Date(), "yyyyMMdd") + df.format(incr);
    }

    /**
     * app借用申请-新增
     * @param extend
     */
    public void add(BorrowApplyExtend extend){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        String userId = jwtTokenUtil.getUserIdFromToken(token).replaceAll("PC_","").replaceAll("APP_","");

        extend.setNumber(getNumber("BRW", orgId));
        extend.setIsDeleted(0);
        extend.setCreateUser(userId);
        extend.setCreateDate(TimeTool.getCurrentTimeStr());
        extend.setUpdateUser(userId);
        extend.setUpdateDate(TimeTool.getCurrentTimeStr());
        extend.setOrgId(orgId);
        borrowApplyMapper.insertSelective(extend);

        TreeSet<String> set = new TreeSet<>();
        for (BorrowApplyAssets asset : extend.getApplyAssetList()) {
            if(StringUtils.isBlank(asset.getAssetId()) || asset.getType()== null || asset.getAssetId() ==  null){
                throw new LogicException("参数错误");
            }

            asset.setBorrowApplyId(extend.getId());
            asset.setState(1);
            asset.setIsDeleted(0);
            asset.setCreateUser(userId);
            asset.setCreateDate(TimeTool.getCurrentTimeStr());
            asset.setUpdateUser(userId);
            asset.setUpdateDate(TimeTool.getCurrentTimeStr());
            borrowApplyAssetsMapper.insertSelective(asset);

            //获取管理员
            List<String> asia = borrowApplyMapper.getModelOrAssetAdmin(orgId, asset.getAssetId(), asset.getType());
            if(!CollectionUtils.isEmpty(asia)){
                set.addAll(asia);
            }
        }
        //给指定分类或资产管理员推送消息
        String[] asia = set.toArray(new String[set.size()]);
        String notification_title = "借用申请";
        String msg_title = "借用申请";
        String msg_content = "借用申请,单据编号：" + extend.getNumber();
        log.info("借用申请,消息推送人："+ JSONObject.toJSONString(asia));
        JpushClientUtil.sendToAsia(asia, notification_title, msg_title, msg_content,"");

        Arrays.stream(asia).forEach(e->{
            PushManagement pu = new PushManagement();
            pu.setCompanyId(orgId);
            pu.setContent(msg_content);
            pu.setCtime(DateTools.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            pu.setCuser(userId);
            pu.setSender(e);
            pu.setResult(0);
            pushMapper.insertSelective(pu);
        });

    }

    /**
     * 更新审批状态
     * @param appParams
     */
    public void updState(ApprovalParams appParams){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();

        //如果已批准，则发放资产
        if(appParams.getState() == 2){

            Example example = new Example(Warehouse.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("assetId", appParams.getAssetIdList());
            criteria.andEqualTo("state", "闲置");
            criteria.andEqualTo("isDelete", 0);
            int count = warehouseMapper.selectCountByExample(example);
//            System.out.println(count);
            if(count == appParams.getAssetIdList().size()){
                Warehouse warehouse = new Warehouse();
                warehouse.setState("待发放");
                warehouseMapper.updateByExampleSelective(warehouse, example);

                BorrowIssueExtend param = new BorrowIssueExtend();
                param.setBorrowUser(appParams.getApplyUser());
                param.setBorrowUserId(appParams.getApplyUserId());
                param.setLendDate(DateTools.dateToString(new Date(), "yyyy-MM-dd"));
                param.setLendUser(userName);
                param.setNote("申请借用发放");
                param.setApplyId(appParams.getId());
                param.setAssetIdList(appParams.getAssetIdList());
                BorrowApply borrowApply = borrowApplyMapper.selBorrowApplyAssetId(appParams.getId());
                param.setExpectBackDate(borrowApply != null ? borrowApply.getExpectBackDate() : "");
                //插入借用发放表
                borowService.add(param);
            }else{
                throw new LogicException("请核实资产状态");
            }

        } else if(appParams.getState() == 3){
            String[] asia = {};
            String notification_title = "借用申请";
            String msg_title = "借用申请";
            String msg_content = "";
            asia = new String[]{appParams.getApplyUserId()};
            msg_content = "借用资产已驳回";
            log.info("借用申请驳回,消息推送人："+ JSONObject.toJSONString(asia));
            JpushClientUtil.sendToAsia(asia, notification_title, msg_title, msg_content,"");

            String finalMsg_content = msg_content;
            Arrays.stream(asia).forEach(e->{
                PushManagement pu = new PushManagement();
                pu.setCompanyId(orgId);
                pu.setContent(finalMsg_content);
                pu.setCtime(DateTools.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
                pu.setCuser(userId);
                pu.setSender(e);
                pu.setResult(0);
                pushMapper.insertSelective(pu);
            });
        }

        //更新申请资产状态
        BorrowApplyAssets applyAssets = new BorrowApplyAssets();
        applyAssets.setId(appParams.getId());
        applyAssets.setState(appParams.getState());
        applyAssets.setUpdateDate(TimeTool.getCurrentTimeStr());
        applyAssets.setUpdateUser(userId);
        borrowApplyAssetsMapper.updateByPrimaryKeySelective(applyAssets);
    }

    /**
     * 分页查询
     * @param params
     * @retu
     */
    public List<BorrowApplyExtend> getAllPage(PageParams<ApplySelParam> params){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        String userId = jwtTokenUtil.getUserIdFromToken(token).replaceAll("PC_","").replaceAll("APP_","");
        PageHelper.startPage(params.getCurrentPage(), params.getPerPageTotal());

        String date = params.getParams().getSelTimeType();
        if("1".equals(date)){
            date = getTime(-1);
        } else if("2".equals(date))  {
            date = getTime(-3);
        } else if("3".equals(date))  {
            date = getTime(-6);
        } else {
            throw new LogicException("查询时间不正确");
        }
        List<BorrowApplyExtend> extendList = borrowApplyMapper.getAllBorrowApply(date, userId, orgId, params.getParams().getState(), null);

        if(extendList != null && extendList.size()>0){
            for (BorrowApplyExtend extend : extendList) {

                //申请明细
                List<BorrowApplyAssetsExtend> applyAssetList = new ArrayList<>();

                Example example = new Example(BorrowApplyAssets.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("state", params.getParams().getState());
                criteria.andEqualTo("borrowApplyId", extend.getId());
                List<BorrowApplyAssets> list = borrowApplyAssetsMapper.selectByExample(example);
                List<BorrowIssueExtend> issueExtendList = new ArrayList<>();
                if(list != null && list.size() > 0){
                    for (BorrowApplyAssets asset : list) {
                        BorrowApplyAssetsExtend assetsExtend = new BorrowApplyAssetsExtend();
                        if(asset.getType() == 1){
                            Warehouse warehouse = warehouseMapper.selectByPrimaryKey(asset.getAssetId());
                            assetsExtend.setAssetCode(warehouse.getAssetCode());
                            assetsExtend.setAssetName(warehouse.getAssetName());
                            assetsExtend.setType(1);
                        } else if(asset.getType() == 2){
                            StandModel model = standModelMapper.selectByPrimaryKey(asset.getAssetId());
                            assetsExtend.setAssetName(model.getName());
                            assetsExtend.setAssetModel(model.getModel());
                            assetsExtend.setUnitMeasurement(model.getType());
                            assetsExtend.setNum(asset.getNum());
                            assetsExtend.setType(2);
                        }
                        applyAssetList.add(assetsExtend);

                        //申请已审批发放明细
                        if(asset.getState() == 2 || asset.getState() == 4){
                            Example example1 = new Example(BorrowIssue.class);
                            Example.Criteria criteria1 = example1.createCriteria();
                            criteria1.andEqualTo("applyId", asset.getId());
//                            if(asset.getState() == 4){
//                                criteria1.andEqualTo("state", 2);
//                            }
//                            else{
//                                criteria1.andEqualTo("state", 1);
//                            }
                            BorrowIssue list1 = borrowIssueMapper.selectOneByExample(example1);
                            BorrowIssueExtend issueExtend = borowService.selById(list1.getId());
                            issueExtendList.add(issueExtend);
                        }
                    }
                }
                extend.setIssueExtendList(issueExtendList);
                extend.setApplyAssetList(applyAssetList);
            }
        }
        return extendList;
    }

    /**
     * 签字后查看详情
     * @param id
     * @return
     */
    public BorrowApplyExtend queryDeail(String id, Integer state){
        List<BorrowApplyExtend> extendList = borrowApplyMapper.getAllBorrowApply(null, null, null, state, id);
        if(extendList != null && extendList.size()>0){
            for (BorrowApplyExtend extend : extendList) {


                //申请明细
                List<BorrowApplyAssetsExtend> applyAssetList = new ArrayList<>();

                List<BorrowIssueExtend> issueExtendList = new ArrayList<>();

                Example example = new Example(BorrowApplyAssets.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("state", state);
                criteria.andEqualTo("borrowApplyId", id);
                List<BorrowApplyAssets> list = borrowApplyAssetsMapper.selectByExample(example);


                if(list != null && list.size() > 0){
                    for (BorrowApplyAssets asset : list) {
                        BorrowApplyAssetsExtend assetsExtend = new BorrowApplyAssetsExtend();
                        if(asset.getType() == 1){
                            Warehouse warehouse = warehouseMapper.selectByPrimaryKey(asset.getAssetId());
                            assetsExtend.setAssetCode(warehouse.getAssetCode());
                            assetsExtend.setAssetName(warehouse.getAssetName());
                            assetsExtend.setType(1);
                        } else if(asset.getType() == 2){
                            StandModel model = standModelMapper.selectByPrimaryKey(asset.getAssetId());
                            assetsExtend.setAssetName(model.getName());
                            assetsExtend.setAssetModel(model.getModel());
                            assetsExtend.setUnitMeasurement(model.getType() == null ? "": model.getType());
                            assetsExtend.setNum(asset.getNum());
                            assetsExtend.setType(2);
                        }
                        applyAssetList.add(assetsExtend);


                        //申请已审批发放明细
                        if(asset.getState() == 4 || asset.getState() == 2){
                            Example example1 = new Example(BorrowIssue.class);
                            Example.Criteria criteria1 = example1.createCriteria();
                            criteria1.andEqualTo("applyId", asset.getId());
                            BorrowIssue list1 = borrowIssueMapper.selectOneByExample(example1);
                            BorrowIssueExtend issueExtend = borowService.selById(list1.getId());
                            issueExtendList.add(issueExtend);
                        }
                    }
                }
                extend.setIssueExtendList(issueExtendList);
                extend.setApplyAssetList(applyAssetList);
            }
        }else{
            return null;
        }
        return extendList.get(0);
    }

    /**
     * 获取几月之前的时间
     * @param num
     * @return
     */
    private String getTime(int num){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, num);
        Date m = c.getTime();
        return format.format(m);
    }
}
